package com.titleevaluation.service;

import com.titleevaluation.entity.AnnualAssessment;
import com.titleevaluation.entity.Application;
import com.titleevaluation.repository.AnnualAssessmentRepository;
import com.titleevaluation.repository.ApplicationRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class AnnualAssessmentService {

    private final AnnualAssessmentRepository annualAssessmentRepository;
    private final ApplicationRepository applicationRepository;

    public AnnualAssessmentService(AnnualAssessmentRepository annualAssessmentRepository, ApplicationRepository applicationRepository) {
        this.annualAssessmentRepository = annualAssessmentRepository;
        this.applicationRepository = applicationRepository;
    }

    public AnnualAssessment createAnnualAssessment(Long applicationId, AnnualAssessment annualAssessment) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        annualAssessment.setApplication(application);
        annualAssessment.setCreatedAt(LocalDateTime.now());
        annualAssessment.setUpdatedAt(LocalDateTime.now());
        return annualAssessmentRepository.save(annualAssessment);
    }

    public List<AnnualAssessment> getAnnualAssessmentsByApplicationId(Long applicationId) {
        return annualAssessmentRepository.findByApplicationId(applicationId);
    }

    public Optional<AnnualAssessment> getAnnualAssessmentById(Long id) {
        return annualAssessmentRepository.findById(id);
    }

    public AnnualAssessment updateAnnualAssessment(Long id, AnnualAssessment annualAssessment) {
        AnnualAssessment existingAnnualAssessment = annualAssessmentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Annual assessment not found"));
        
        existingAnnualAssessment.setYear(annualAssessment.getYear());
        existingAnnualAssessment.setTechnicalQualification(annualAssessment.getTechnicalQualification());
        existingAnnualAssessment.setAssessmentResult(annualAssessment.getAssessmentResult());
        existingAnnualAssessment.setRemarks(annualAssessment.getRemarks());
        existingAnnualAssessment.setUpdatedAt(LocalDateTime.now());
        
        return annualAssessmentRepository.save(existingAnnualAssessment);
    }

    public void deleteAnnualAssessment(Long id) {
        annualAssessmentRepository.deleteById(id);
    }
}

